﻿using BlazorComponent;
using ImoviesBlazor.Shared.Dtos;
using ImoviesBlazor.Shared.Utils;
using System.Net.Http.Json;
using System.Text.Json;

namespace ImoviesBlazor.Client.Pages.admin
{
    public partial class Vmanage
    {

        /// <summary>
        /// 表格展示用类
        /// </summary>
        public class TableViewModel
        {
            public string Id { get; set; }
            public string Name { get; set; }
            public string Url { get; set; }
            public string Category { get; set; }
            public string Region { get; set; }
            public uint Year { get; set; }
            public string Actors { get; set; }
            public string Director { get; set; }
            public string Intro { get; set; }
            public string Img { get; set; }
            public string Comment { get; set; }

            public TableViewModel() { }

            public TableViewModel(string id, string name, string url, string category, string region, uint year, string actors, string director, string intro, string img, string comment)
            {
                Id = id;
                Name = name;
                Url = url;
                Category = category;
                Region = region;
                Year = year;
                Actors = actors;
                Director = director;
                Intro = intro;
                Img = img;
                Comment = comment;
            }
        }

        /// <summary>
        /// 视频类型选择类
        /// </summary>
        public class SelectItem
        {
            public string Label { get; set; }
            public string Value { get; set; }

            public SelectItem(string label, string value)
            {
                this.Label = label;
                this.Value = value;
            }
        }

        /// <summary>
        /// 表头定义
        /// </summary>
        public List<DataTableHeader<TableViewModel>> headers = new List<DataTableHeader<TableViewModel>>
        {
            new (){ Text= "Id", Value= nameof(TableViewModel.Id),Sortable=false,Width="80px",Align="center"},
            new (){ Text= "名称", Value= nameof(TableViewModel.Name),Align="center"},
            new (){ Text= "地址", Value= nameof(TableViewModel.Url),Sortable=false,Width="50px", Align="center"},
            new (){ Text= "分类", Value= nameof(TableViewModel.Category),Sortable=false,Align="center"},
            new (){ Text= "地区", Value= nameof(TableViewModel.Region),Sortable=false,Width="100px",Align="center"},
            new (){ Text= "年份", Value= nameof(TableViewModel.Year),Width="100px",Align="center"},
            new (){ Text= "主演", Value= nameof(TableViewModel.Actors),Sortable=false,Width="100px",Align="center"},
            new (){ Text= "导演", Value= nameof(TableViewModel.Director),Sortable=false,Width="100px",Align="center"},
            new (){ Text= "点评", Value= nameof(TableViewModel.Comment),Sortable=false,Width="200px", Align="center"},
            new (){ Text= "图片", Value= nameof(TableViewModel.Img),Sortable=false,Width="50px", Align="center"},
            new (){ Text= "简介", Value= nameof(TableViewModel.Intro),Sortable=false,Width="50px", Align="center"},
            new (){ Text= "操作", Value= "actions",Sortable=false,Width="100px",Align="center" }
        };

        /// <summary>
        /// 显示到表格的视频数据
        /// </summary>
        public List<TableViewModel> videoList = new List<TableViewModel>();

        /// <summary>
        /// 被选中的视频分类
        /// </summary>
        public string selectedVideoCate = null;

        public bool _dialogEdit;
        public bool _dialogAdd;
        public bool _dialogDelete;

        List<SelectItem> selectItems = new()
        {
            new SelectItem("电视剧", "电视剧"),
            new SelectItem("电影", "电影"),
            new SelectItem("动漫", "动漫")
        };


        public TableViewModel _editedItem = new TableViewModel();
        public TableViewModel _addItem = new TableViewModel();

        /// <summary>
        /// 关闭对话框
        /// </summary>
        public void Close()
        {
            _dialogEdit = false;
            _dialogAdd = false;
            _editedItem = new TableViewModel();
            _addItem = new TableViewModel();
        }

        /// <summary>
        /// 显示添加表单
        /// </summary>
        public void ShowAddForm()
        {
            if (string.IsNullOrEmpty(selectedVideoCate))
            {
                return;
            }
            _dialogAdd = true;
        }

        /// <summary>
        /// 提交编辑
        /// </summary>
        public async Task SubmitEdit()
        {
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    TeleplayForUpdateDto tdata = new TeleplayForUpdateDto
                    {
                        Id = _editedItem.Id,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,
                        Category = _editedItem.Category,
                        Region = _editedItem.Region,
                        Year = _editedItem.Year,
                        Actors = _editedItem.Actors,
                        Director = _editedItem.Director,
                        Comment = _editedItem.Comment,
                        Img = _editedItem.Img,
                        Intro = _editedItem.Intro,
                    };
                    res = await HttpClient.PutAsJsonAsync<TeleplayForUpdateDto>("/api/teleplay", tdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetTeleplays();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "电影":
                    MovieForUpdateDto mdata = new MovieForUpdateDto
                    {
                        Id = _editedItem.Id,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,
                        Category = _editedItem.Category,
                        Region = _editedItem.Region,
                        Year = _editedItem.Year,
                        Actors = _editedItem.Actors,
                        Director = _editedItem.Director,
                        Comment = _editedItem.Comment,
                        Img = _editedItem.Img,
                        Intro = _editedItem.Intro,
                    };
                    res = await HttpClient.PutAsJsonAsync<MovieForUpdateDto>("/api/movie", mdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetMovies();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "动漫":
                    AnimationForUpdateDto adata = new AnimationForUpdateDto
                    {
                        Id = _editedItem.Id,
                        Name = _editedItem.Name,
                        Url = _editedItem.Url,
                        Category = _editedItem.Category,
                        Region = _editedItem.Region,
                        Year = _editedItem.Year,
                        Actors = _editedItem.Actors,
                        Director = _editedItem.Director,
                        Comment = _editedItem.Comment,
                        Img = _editedItem.Img,
                        Intro = _editedItem.Intro,
                    };
                    res = await HttpClient.PutAsJsonAsync<AnimationForUpdateDto>("/api/animation", adata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogEdit = false;
                        _editedItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetAnimations();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 提交添加
        /// </summary>
        public async Task SubmitAddAsync()
        {
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    TeleplayForCreateDto tdata = new TeleplayForCreateDto
                    {
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        Category = _addItem.Category,
                        Region = _addItem.Region,
                        Year = _addItem.Year,
                        Actors = _addItem.Actors,
                        Director = _addItem.Director,
                        Comment = _addItem.Comment,
                        Img = _addItem.Img,
                        Intro = _addItem.Intro,
                    };
                    res = await HttpClient.PostAsJsonAsync<TeleplayForCreateDto>("/api/teleplay", tdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetTeleplays();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "电影":
                    MovieForCreateDto mdata = new MovieForCreateDto
                    {
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        Category = _addItem.Category,
                        Region = _addItem.Region,
                        Year = _addItem.Year,
                        Actors = _addItem.Actors,
                        Director = _addItem.Director,
                        Comment = _addItem.Comment,
                        Img = _addItem.Img,
                        Intro = _addItem.Intro,
                    };
                    res = await HttpClient.PostAsJsonAsync<MovieForCreateDto>("/api/movie", mdata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetMovies();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "动漫":
                    AnimationForCreateDto adata = new AnimationForCreateDto
                    {
                        Name = _addItem.Name,
                        Url = _addItem.Url,
                        Category = _addItem.Category,
                        Region = _addItem.Region,
                        Year = _addItem.Year,
                        Actors = _addItem.Actors,
                        Director = _addItem.Director,
                        Comment = _addItem.Comment,
                        Img = _addItem.Img,
                        Intro = _addItem.Intro,
                    };
                    res = await HttpClient.PostAsJsonAsync<AnimationForCreateDto>("/api/animation", adata);
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogAdd = false;
                        _addItem = new TableViewModel();
                        // 重载数据
                        videoList = await GetAnimations();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }

        }

        /// <summary>
        /// 编辑按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void EditItem(TableViewModel item)
        {
            _editedItem = item;
            _dialogEdit = true;
        }

        /// <summary>
        /// 待删除的记录id
        /// </summary>
        private string awaitDelId = string.Empty;
        /// <summary>
        /// 删除按钮点击
        /// </summary>
        /// <param name="item"></param>
        public void DeleteItem(string itemId)
        {
            awaitDelId = itemId;
            _dialogDelete = true;
        }

        /// <summary>
        /// 提交删除
        /// </summary>
        public async Task DeleteItemConfirmAsync()
        {
            if (string.IsNullOrEmpty(awaitDelId))
            {
                return;
            }
            HttpResponseMessage res;
            switch (selectedVideoCate)
            {
                case "电视剧":
                    res = await HttpClient.DeleteAsync($"/api/teleplay/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        // 重载数据
                        videoList = await GetTeleplays();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "电影":
                    res = await HttpClient.DeleteAsync($"/api/movie/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        // 重载数据
                        videoList = await GetMovies();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                case "动漫":
                    res = await HttpClient.DeleteAsync($"/api/animation/{awaitDelId}");
                    if (res.IsSuccessStatusCode || (int)res.StatusCode == 200)
                    {
                        _dialogDelete = false;
                        // 重载数据
                        videoList = await GetAnimations();
                        return;
                    }
                    await PopupService.ToastAsync((config) =>
                    {
                        config.Title = "操作失败";
                        config.Duration = 1;
                        config.Type = BlazorComponent.AlertTypes.Error;
                    });
                    break;
                default:
                    break;
            }

            CloseDelete();
        }

        /// <summary>
        /// 关闭删除对话框
        /// </summary>
        public void CloseDelete()
        {
            _dialogDelete = false;
            awaitDelId = string.Empty;
            _editedItem = new TableViewModel();
        }


        /// <summary>
        /// 视频类型选择改变
        /// </summary>
        /// <returns></returns>
        public async Task VcateSelectedChange(string value)
        {
            selectedVideoCate = value;
            switch (value)
            {
                case "电视剧":
                    videoList = await GetTeleplays();
                    break;
                case "电影":
                    videoList = await GetMovies();
                    break;
                case "动漫":
                    videoList = await GetAnimations();
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 视频类型选择下拉框清空事件
        /// </summary>
        public void ClearVcate()
        {
            selectedVideoCate = null;
            videoList = new List<TableViewModel>();
        }

        /// <summary>
        /// 获取全部电视剧
        /// </summary>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetTeleplays()
        {
            var resp = await HttpClient.GetAsync("api/teleplay/all");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }

        /// <summary>
        /// 获取全部电影
        /// </summary>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetMovies()
        {
            var resp = await HttpClient.GetAsync("api/movie/all");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }

        /// <summary>
        /// 获取全部动漫
        /// </summary>
        /// <returns></returns>
        private async Task<List<TableViewModel>> GetAnimations()
        {
            var resp = await HttpClient.GetAsync("api/animation/all");
            var resData = JsonSerializer.Deserialize<List<TableViewModel>>(await resp.Content.ReadAsStringAsync(),
             new JsonSerializerOptions
             {
                 PropertyNameCaseInsensitive = true,
                 IncludeFields = true,
             });

            return resData ?? new List<TableViewModel>();
        }


    }
}
